package br.com.projfinal.persistence;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.projfinal.util.HibernateUtil;

public abstract class GenericDaoHibernate<E, ID extends Serializable> implements GenericDao<E, ID> {

	protected Session s;
	protected Transaction t;
	protected Criteria c;
	protected Query q;
	
	private Class<E> entity;
	
	public GenericDaoHibernate(Class<E> entity){
		this.entity = entity;		
	}

	@Override
	public void delete(E entity) throws Exception {
		s = HibernateUtil.getInstance();
		t = s.beginTransaction();
		s.delete(entity);
		t.commit();
	}

	@SuppressWarnings("unchecked")
	@Override
	public E find(ID key) throws Exception {
		s = HibernateUtil.getInstance();
		return (E) s.get(entity, key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findAll() throws Exception {
		s = HibernateUtil.getInstance();
		c = s.createCriteria(entity);
		return c.list();
	}

	@Override
	public void save(E entity) throws Exception {
		s = HibernateUtil.getInstance();
		t = s.beginTransaction();
		s.save(entity);
		t.commit();
	}

	@Override
	public void update(E entity) throws Exception {
		s = HibernateUtil.getInstance();
		t = s.beginTransaction();
		s.update(entity);
		t.commit();
	}
	
}
